package com.yazi.mxz.common.service.impl;

import java.util.HashSet;

import javax.annotation.Resource;

import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.db.dao.AdminDao;
import com.yazi.mxz.common.db.dao.AdminRoleDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Admin;
import com.yazi.mxz.common.entity.beans.AdminRole;
import com.yazi.mxz.common.entity.beans.AdminRoleId;
import com.yazi.mxz.common.service.AdminService;

@Service("adminService")
public class AdminServiceImpl extends BasicService<Admin> implements AdminService {
	private static Logger log = LoggerFactory.getLogger(AdminServiceImpl.class);
	
	@Resource
	AdminDao adminDao;
	@Resource
	AdminRoleDao adminRoleDao;
	
	@Override
	protected Dao<Admin> getDao() {
		return adminDao;
	}
	
	@Override
	public void editRoleForAdminId(long adminId, long[] roleIds) {
		log.debug("modifyRoleForAdminId：adminId={},roleIds={}", adminId, roleIds);
		
		// 解除所有角色的绑定
		Admin admin = adminDao.get(adminId);
		admin.setAdminRoles(new HashSet<AdminRole>());
		adminDao.merge(admin);
		
		// 绑定角色
		if (null != roleIds) {
			for (Long roleId : roleIds) {
				AdminRole adminRole = new AdminRole();
				AdminRoleId id = new AdminRoleId();
				id.setRoleId(roleId);
				id.setAdminId(adminId);
				adminRole.setId(id);
				adminRoleDao.persist(adminRole);
			}
		}
		
	}

	@Override
	public Admin addOrEdit(Admin admin) {
		if (null != admin.getAdminId()) {
			log.debug("addOrModify->modify：adminId={}", admin.getAdminId());
			
			// 防止篡改登录名
			admin.setName(null);
			
			// 密码不为空时修改密码
			if (null != admin.getPassword() && !admin.getPassword().isEmpty()) {
				admin.setPassword(MyUtil.encodePwd(admin.getPassword()));
			} else {
				admin.setPassword(null);
			}
			Admin oldAdmin = adminDao.get(admin.getAdminId());
			ValueFactory.combine(admin, oldAdmin);
			return adminDao.merge(oldAdmin);
			
		} else {
			log.debug("addOrModify->add：name={}", admin.getName());
			
			ValueFactory.validate(admin);
			admin.setPassword(MyUtil.encodePwd(admin.getPassword()));
			admin.setAdminId(null);
			return adminDao.persist(admin);
		}
	}

}
